//
//  String+Ext.swift
//  KLExtension
//
//  Created by nkl on 2023/6/29.
//

import Foundation

extension String {
    public var `extension`: String {
        if let index = lastIndex(of: ".") {
            return String(self[index...])
        } else {
            return ""
        }
    }

    /// 获取内容高度
    public func contentHeight(font: UIFont, maxWidth: CGFloat) -> CGFloat {
        let attributes = [NSAttributedString.Key.font: font]
        let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
        let rect = self.boundingRect(with: CGSize(width: maxWidth, height: .greatestFiniteMagnitude), options: options, attributes: attributes, context: nil)
        let height = rect.size.height
        return height
    }

    public var isValidURL: Bool {
        let urlRegex = #"^(https?://)?([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$"#
        let urlTest = NSPredicate(format: "SELF MATCHES %@", urlRegex)
        return urlTest.evaluate(with: self)
    }

    // MARK: - 获取十六进制的值

    public func hexValue() -> Int {
        let str = uppercased()
        var sum = 0
        for i in str.utf8 {
            sum = sum * 16 + Int(i) - 48 // 0-9 从48开始
            if i >= 65 { // A-Z 从65开始，但有初始值10，所以应该是减去55
                sum -= 7
            }
        }
        return sum
    }
}
